package com.coodean.mybatis.demo;

import com.coodean.mybatis.demo.dao.AuthorDao;
import com.coodean.mybatis.demo.entity.Author;
import org.apache.ibatis.session.SqlSession;

/**
 * Created by weichengke on 6/25/17.
 */
public class Application {

    private Long id = 1L;
    private String sqlNamespace = "AuthorDao";

    private void testInsert() {
        Author author = new Author();
        author.setId(id);
        author.setUsername("dev");
        author.setPassword("123456");
        author.setEmail("dev@coodean.com");
        author.setBio("I am cool website");
        try (SqlSession session = MybatisXmlUtil.getSession()) {
            session.insert(sqlNamespace+".insert", author);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("insert ==>" + author);
    }

    private void testSelect() {
        try (SqlSession session = MybatisXmlUtil.getSession()) {
            Author author = session.selectOne(sqlNamespace+".select", id);
            System.out.println("select ==> " + author);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void testUpdate() {
        try (SqlSession session = MybatisXmlUtil.getSession()) {
            Author author = new Author();
            author.setId(id);
            author.setUsername("dev");
            author.setPassword("******");
            author.setEmail("dev@coodean.com");
            author.setBio("I am very cool website");
            AuthorDao authorDao = session.getMapper(AuthorDao.class);
            authorDao.update(author);
            session.commit();
            System.out.println("update ==> " + author);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void testDelete() {
        try (SqlSession session = MybatisXmlUtil.getSession()) {
            AuthorDao authorDao = session.getMapper(AuthorDao.class);
            authorDao.delete(id);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Application application = new Application();
        application.testInsert();
        application.testSelect();
        application.testUpdate();
        application.testDelete();
    }
}
